package com.business.activiti.listener;

import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyActivitiEventListener implements ActivitiEventListener {
    @Autowired
    ProcessStartListener processStartListener;
    @Autowired
    TaskCreateListener taskCreateListener;

    @Autowired
    TaskCompleteListener taskCompleteListener;

    private Map<ActivitiEventType, EventHandler> handlers = new HashMap<ActivitiEventType, EventHandler>();

    public static MyActivitiEventListener myActivitiEventListener;

    @PostConstruct
    public void init(){
        myActivitiEventListener = this;
        myActivitiEventListener.taskCreateListener = this.taskCreateListener;
        myActivitiEventListener.taskCompleteListener = this.taskCompleteListener;
        myActivitiEventListener.processStartListener = this.processStartListener;
        handlers.put(ActivitiEventType.TASK_CREATED,this.taskCreateListener);
        handlers.put(ActivitiEventType.TASK_COMPLETED,this.taskCompleteListener);
        handlers.put(ActivitiEventType.PROCESS_STARTED,this.processStartListener);
    }

    @Override
    public void onEvent(ActivitiEvent event) {
        EventHandler eventHandler = handlers.get(event.getType());
        if(eventHandler!=null){
            eventHandler.handle(event);
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}
